cocos2d-x simple shader usage [on hold]

Posted by Narek on Game Development See other posts from Game Development or by Narek
Published on 2014-08-24T09:07:24Z Indexed on 2014/08/24 10:31 UTC
Read the original article Hit count: 293

I want to obtain color ramp effect from this tutorial: http://www.raywenderlich.com/10862/how-to-create-cool-effects-with-custom-shaders-in-opengl-es-2-0-and-cocos2d-2-x

Here is my code in cocos2d-x 3:

bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Vec2 origin = Director::getInstance()->getVisibleOrigin();


    sprite = Sprite::create("HelloWorld.png");
    sprite->setAnchorPoint(Vec2(0, 0));
    sprite->setRotation(3);
    sprite->setPosition(origin);
    addChild(sprite);

    std::string str = FileUtils::getInstance()->getStringFromFile("CSEColorRamp.fsh");

    const GLchar * fragmentSource = str.c_str();
    GLProgram* p = GLProgram::createWithByteArrays(ccPositionTextureA8Color_vert, fragmentSource);


    p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
    p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD);
    p->link();
    p->updateUniforms();

    sprite->setGLProgram(p);


    // 3
    colorRampUniformLocation = glGetUniformLocation(sprite->getGLProgram()->getProgram(), "u_colorRampTexture");
    glUniform1i(colorRampUniformLocation, 1);

    // 4
    colorRampTexture = Director::getInstance()->getTextureCache()->addImage("colorRamp.png");
    colorRampTexture->setAliasTexParameters();

    // 5
    sprite->getGLProgram()->use();
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, colorRampTexture->getName());
    glActiveTexture(GL_TEXTURE0);

    return true;
}

And here is the fragment shader as it is in the tutorial:

#ifdef GL_ES
precision mediump float;
#endif

// 1
varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform sampler2D u_colorRampTexture;

void main()
{ // 2
  vec3 normalColor = texture2D(u_texture, v_texCoord).rgb;

  // 3
  float rampedR = texture2D(u_colorRampTexture, vec2(normalColor.r, 0)).r;
  float rampedG = texture2D(u_colorRampTexture, vec2(normalColor.g, 0)).g;
  float rampedB = texture2D(u_colorRampTexture, vec2(normalColor.b, 0)).b;

  // 4
  gl_FragColor = vec4(rampedR, rampedG, rampedB, 1);
} 

As a result I get a black screen with 2 draw calls. What is wrong? Do I miss something?

© Game Development or respective owner

Related posts about opengl

Related posts about shaders